package org.fujene.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.fujene.structure.Constants;
import org.msgpack.MessagePackObject;
import org.msgpack.rpc.Client;

/**
 * 簡単なクライアントプログラムです。
 * 標準入力で操作します。
 * 主にテスト用途に用います。
 */
public class SimpleClient implements Runnable{	
//	public void runClient(String address) throws IOException {
	@Override
	public void run() {
		Client indexClient = null;
		Client searchClient = null;
		try {
			System.out.println("Connecting...");
			// サーバが立ち上がるまで待ち
			Thread.sleep(1000);
			
			indexClient = new Client("127.0.0.1", Constants.INDEX_PORT);
			searchClient = new Client("127.0.0.1", Constants.SEARCH_PORT);

			System.out.println(" Done.");

			// Searching, Indexingとの送受信ストリーム
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String input = null;
			while(true){
				System.out.print("データ読み出し(r), データ出力(w), 検索(s), 追加(i), 終了(q) -> ");
				input = br.readLine();
				if (input.equals("s")) {
					// 検索
					System.out.print("\tクエリを入力 -> ");
					input = br.readLine();
					
					MessagePackObject result = searchClient.callApply("search", new Object[]{input});
					
					if(!result.isNil()){
						MessagePackObject[] objs = result.asArray();
						
						for (int i = 0; i < objs.length; i++) {
							System.out.println("Output: " + objs[i].asString());
						}
						
						System.out.println("Recieved amount: " + objs.length);
					}
				}else if (input.equals("i")) {
					// Indexing
					System.out.print("\t文章を入力 -> ");
					input = br.readLine();
					
					indexClient.callApply("index", new Object[]{input});
				}else if (input.equals("q")) {
					indexClient.callApply("stop", new Object[]{});
					searchClient.callApply("stop", new Object[]{});
					
					break;
				}else if (input.equals("r")) {
					indexClient.callApply("read", new Object[]{});
				}else if (input.equals("w")) {
					indexClient.callApply("save", new Object[]{});
				}else{
				}
				
				Thread.sleep(200);
			}
			System.out.println("Client closed.");
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException ignored) {
		}finally{
			indexClient.close();
			searchClient.close();
		}
	}
}
